<template>
  <div class="app-container">
    <template v-if="EditInterName === false">
      <el-link
        v-if="isEdit === true"
        :underline="false"
        type="success"
        style="float: right"
        @click="copyInter"
      >
        复制接口
      </el-link>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>
          {{ idCollection.proName }}
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span style="color: red">* </span>
          {{ interName }}
          <i
            v-if="isEdit === false"
            class="el-icon-edit"
            @click.stop="EditInterName = true"
            ><span style="color: gray">请输入接口名称</span></i
          >
        </el-breadcrumb-item>
      </el-breadcrumb>
    </template>
    <template v-else>
      <el-input
        type="text"
        v-model="interName"
        size="mini"
        @blur="EditInterName = false"
        placeholder="请输入接口名称"
        v-focus
      ></el-input>
    </template>
    <el-divider></el-divider>
    <div v-loading="loading">
      <div class="dms-input">
        <el-input
          placeholder="请输入网址"
          v-model="requestUrl"
          class="input-with-select"
          :disabled="isEdit"
          @blur="segmentationParam"
        >
          <el-select
            v-model="requestMethod"
            slot="prepend"
            placeholder="请选择"
            :disabled="isEdit"
            style="color: black"
          >
            <el-option label="GET" value="1"></el-option>
            <el-option label="POST" value="2"></el-option>
            <el-option label="PUT" value="3"></el-option>
            <el-option label="PATCH" value="4"></el-option>
            <el-option label="DELETE" value="5"></el-option>
          </el-select>
        </el-input>
        <el-button
          type="primary"
          style="margin-left: 10px"
          @click="sendRequest"
          v-if="AddOrEdit === 'Edit'"
          v-preventReClick
          >发送请求</el-button
        >
        <el-button
          type="success"
          style="margin-left: 10px"
          @click="saveRequest"
          v-if="isEdit === false"
          v-preventReClick
          >保存接口</el-button
        >
        <el-button
          type="success"
          style="margin-left: 10px"
          @click="isEdit = false"
          v-else
          v-preventReClick
          >编辑接口</el-button
        >
      </div>
      <template>
        <el-tabs v-model="activeName">
          <el-tab-pane label="参数" name="first">
            <div class="tab-content">
              <span style="color: rgb(107, 107, 107)">查询参数</span>
              <template>
                <el-table
                  :data="tableData"
                  height="250"
                  border
                  style="width: 100%"
                  highlight-current-row
                  @cell-click="cellClick"
                  :cell-class-name="tableCellClassName"
                >
                  <el-table-column prop="index" label="" width="100">
                  </el-table-column>
                  <el-table-column prop="key" label="KEY" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <el-input
                        v-if="
                          scope.row.index === cellRowIndex &&
                          scope.column.index === cellColumnIndex &&
                          isEdit === false
                        "
                        v-model="scope.row.key"
                        size="mini"
                        placeholder="Key"
                        ref="editInput"
                        @blur="changeValue"
                      />
                      <span v-else style="color: black">
                        {{ scope.row.key || "" }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="value"
                    label="VALUE"
                    show-overflow-tooltip
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-if="
                          scope.row.index === cellRowIndex &&
                          scope.column.index === cellColumnIndex &&
                          isEdit === false
                        "
                        v-model="scope.row.value"
                        size="mini"
                        placeholder="Value"
                        ref="editInput"
                        @blur="changeValue"
                      />
                      <span v-else style="color: black">
                        {{ scope.row.value || "" }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="description"
                    label="DESCRIPTION"
                    show-overflow-tooltip
                  >
                    <template slot-scope="scope">
                      <!-- <el-button
                        v-if="
                          isEdit === false &&
                          (scope.row.hasOwnProperty('key') ||
                            scope.row.hasOwnProperty('value'))
                        "
                        @click.native.prevent="
                          deleteRow(scope.$index, tableData)
                        "
                        type="text"
                        size="small"
                      >
                        移除
                      </el-button> -->
                      <el-input
                        v-if="
                          scope.row.index === cellRowIndex &&
                          scope.column.index === cellColumnIndex &&
                          isEdit === false
                        "
                        v-model="scope.row.description"
                        size="mini"
                        placeholder="Description"
                        ref="editInput"
                        @blur="changeValue"
                        :disabled="isEdit"
                      />
                      <span v-else style="color: black">
                        {{ scope.row.description || "" }}
                      </span>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column prop="" label="操作" width="100">
                  <template slot-scope="scope">
                    <el-button type="text">删除{{ scope.row.key }}</el-button>
                  </template>
                </el-table-column> -->
                </el-table>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="请求头" name="second">
            <div class="tab-content">
              <span style="color: rgb(107, 107, 107)">请求头参数</span>
              <template>
                <el-table
                  :data="headerData"
                  height="250"
                  border
                  style="width: 100%"
                  highlight-current-row
                  @cell-click="headerCellClick"
                  :cell-class-name="headerTableCellClassName"
                >
                  <el-table-column prop="index" label="" width="100">
                  </el-table-column>
                  <el-table-column prop="key" label="KEY" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <el-input
                        v-if="
                          scope.row.index === headerCellRowIndex &&
                          scope.column.index === headerCellColumnIndex &&
                          isEdit === false
                        "
                        v-model="scope.row.key"
                        size="mini"
                        placeholder="Key"
                        ref="editInput"
                        @blur="headerChangeValue"
                      />
                      <span v-else>
                        {{ scope.row.key || "" }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="value"
                    label="VALUE"
                    show-overflow-tooltip
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-if="
                          scope.row.index === headerCellRowIndex &&
                          scope.column.index === headerCellColumnIndex &&
                          isEdit === false
                        "
                        v-model="scope.row.value"
                        size="mini"
                        placeholder="Value"
                        ref="editInput"
                        @blur="headerChangeValue"
                      />
                      <span v-else>
                        {{ scope.row.value || "" }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="description"
                    label="DESCRIPTION"
                    show-overflow-tooltip
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-if="
                          scope.row.index === headerCellRowIndex &&
                          scope.column.index === headerCellColumnIndex &&
                          isEdit === false
                        "
                        v-model="scope.row.description"
                        size="mini"
                        placeholder="Description"
                        ref="editInput"
                        @blur="headerChangeValue"
                        :disabled="isEdit"
                      />
                      <span v-else>
                        {{ scope.row.description || "" }}
                      </span>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column prop="" label="操作" width="100">
                  <template slot-scope="scope">
                    <el-button type="text">删除{{ scope.row.key }}</el-button>
                  </template>
                </el-table-column> -->
                </el-table>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="Body请求体" name="third">
            <div class="tab-content">
              <div class="radioMenu">
                <template>
                  <el-form :inline="true" :model="formInline" size="mini">
                    <el-form-item>
                      <template>
                        <el-radio-group
                          v-model="formInline.radio"
                          :disabled="isEdit"
                        >
                          <el-radio label="none">none</el-radio>
                          <el-radio label="formData">form-data</el-radio>
                          <el-radio label="raw">raw</el-radio>
                        </el-radio-group>
                      </template>
                    </el-form-item>
                    <el-form-item v-show="formInline.radio === 'raw'">
                      <el-select
                        v-model="formInline.value"
                        placeholder="请选择"
                        size="mini"
                        style="margin-left: 20px"
                        :disabled="isEdit"
                      >
                        <el-option
                          v-for="item in options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-form>
                </template>
              </div>
              <div class="showInfo">
                <div v-if="formInline.radio === 'none'" class="none-style">
                  <span>这个请求不包含body</span>
                </div>
                <div v-else-if="formInline.radio === 'formData'">
                  <el-table
                    :data="bodyData"
                    height="250"
                    border
                    style="width: 100%"
                    highlight-current-row
                    @cell-click="bodyCellClick"
                    :cell-class-name="bodyTableCellClassName"
                  >
                    <el-table-column prop="index" label="" width="100">
                    </el-table-column>
                    <el-table-column
                      prop="key"
                      label="KEY"
                      show-overflow-tooltip
                    >
                      <template slot-scope="scope">
                        <el-input
                          v-if="
                            scope.row.index === bodyCellRowIndex &&
                            scope.column.index === bodyCellColumnIndex
                          "
                          v-model="scope.row.key"
                          size="mini"
                          placeholder="Key"
                          ref="editInput"
                          @blur="bodyChangeValue"
                        />
                        <span v-else style="color: black">
                          {{ scope.row.key || "" }}
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="value"
                      label="VALUE"
                      show-overflow-tooltip
                    >
                      <template slot-scope="scope">
                        <el-input
                          v-if="
                            scope.row.index === bodyCellRowIndex &&
                            scope.column.index === bodyCellColumnIndex
                          "
                          v-model="scope.row.value"
                          size="mini"
                          placeholder="Value"
                          ref="editInput"
                          @blur="bodyChangeValue"
                        />
                        <span v-else style="color: black">
                          {{ scope.row.value || "" }}
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="description"
                      label="DESCRIPTION"
                      show-overflow-tooltip
                    >
                      <template slot-scope="scope">
                        <el-input
                          v-if="
                            scope.row.index === bodyCellRowIndex &&
                            scope.column.index === bodyCellColumnIndex
                          "
                          v-model="scope.row.description"
                          size="mini"
                          placeholder="Description"
                          ref="editInput"
                          @blur="bodyChangeValue"
                        />
                        <span v-else style="color: black">
                          {{ scope.row.description || "" }}
                        </span>
                      </template>
                    </el-table-column>
                    <!-- <el-table-column prop="" label="操作" width="100">
                    <template slot-scope="scope">
                      <el-button type="text">删除{{ scope.row.key }}</el-button>
                    </template>
                  </el-table-column> -->
                  </el-table>
                </div>
                <div v-else-if="formInline.radio === 'raw'">
                  <el-input
                    type="textarea"
                    :autosize="{ minRows: 11, maxRows: 11 }"
                    placeholder="请输入内容"
                    :disabled="isEdit"
                    v-model="bodyTextData"
                  ></el-input>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </template>
      <div>
        <div class="title">
          <span>响应</span>
        </div>
        <div class="response-content">
          <div v-if="returnResult">
            <pre
              style="text-align: left; color: #67c23a"
              v-if="resultShow === 'success'"
              >{{ returnData }}</pre
            >
            <pre
              style="text-align: left; color: red"
              v-if="resultShow === 'error'"
              >{{ returnData }}</pre
            >
          </div>
          <div v-else>
            <img src="@/assets/images/noSend.png" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getInterface,
  addInterface,
  updateInterface,
  dmsExecute,
} from "@/api/dmsIms/interface";
import {
  interListGlobalvar,
  updateGlobalvar,
  getGlobalvarbyName,
} from "@/api/dmsIms/globalvar";
// 未完成: 表单数据清空后，该行应该删除
export default {
  name: "RequestData",
  props: ["idCollection"],
  directives: {
    // 自动聚焦
    focus: {
      inserted: function (el) {
        // console.log(el);
        //因为el-input这是个组件，input外面被一层 div 包裹着
        //el打印出来是外面这个 div，需要找到内层的input
        el.children[0].focus();
      },
    },
  },
  watch: {
    idCollection: {
      handler() {
        this.initPage();
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {},
  data() {
    return {
      url: "",
      requestUrl: "",
      requestMethod: "1",
      returnResult: false,
      resultShow: "success",
      returnData: "",
      cellRowIndex: null,
      cellColumnIndex: null,
      headerCellRowIndex: null,
      headerCellColumnIndex: null,
      bodyCellRowIndex: null,
      bodyCellColumnIndex: null,
      activeName: "first",
      tableData: [{}],
      headerData: [{}],
      bodyData: [{}],
      bodyTextData: "",
      isEdit: false,
      AddOrEdit: "Add",
      formInline: {
        radio: "none",
        value: "json",
      },
      options: [
        {
          value: "json",
          label: "JSON",
        },
        {
          value: "javascript",
          label: "JavaScript",
        },
        {
          value: "text",
          label: "Text",
        },
      ],
      loading: false,
      interName: "",
      EditInterName: false,
      interAddData: {},
      // isShowTipLeave: false,
    };
  },
  methods: {
    async sendRequest() {
      this.returnData = "";
      // 请求的信息
      let allRequestData = {
        id: this.idCollection.interId,
        url: this.requestUrl,
        method: this.requestMethod,
        header: this.combineHeader(),
        body: this.bodyValue(),
        bodyType: this.formInline.radio,
      };
      await this.matchReplace(allRequestData);
      // console.log(allRequestData);
      // 1、url、header、body分别进行匹配 --- ${}
      // 2、匹配到值，进行查询，用查询到的值替换匹配到的值。
      this.excuteDmsInter(allRequestData);
    },
    async matchReplace(value) {
      //匹配并替换变量
      let rule = /\${(.+?)}/g;
      const arr = [...value.url.matchAll(rule)];
      if (arr.length > 0) {
        for (let temp of arr) {
          let res = "";
          await getGlobalvarbyName(temp[1])
            .then((response) => {
              res = response.data.varValue;
              value.url = value.url.replace(temp[0], res);
            })
            .catch((error) => {});
        }
      }
      const arr1 = [...value.header.matchAll(rule)];
      if (arr1.length > 0) {
        for (let temp of arr1) {
          let res = "";
          await getGlobalvarbyName(temp[1])
            .then((response) => {
              res = response.data.varValue;
              value.header = value.header.replace(temp[0], res);
            })
            .catch((error) => {});
        }
      }
      const arr2 = [...value.body.matchAll(rule)];
      if (arr2.length > 0) {
        for (let temp of arr2) {
          let res = "";
          await getGlobalvarbyName(temp[1])
            .then((response) => {
              res = response.data.varValue;
              value.body = value.body.replace(temp[0], res);
            })
            .catch((error) => {});
        }
        // arr.forEach((elem) => {
        //   let res = "";
        //   getGlobalvarbyName(elem[1]).then((response) => {
        //     res = response.data.varValue;
        //     value = value.replace(elem[0], res);
        //   });
        // });
      }
    },
    excuteDmsInter(allRequestData) {
      dmsExecute(allRequestData)
        .then((response) => {
          if (Object.keys(response.data).length !== 0) {
            if (response.data.hasOwnProperty("errorMsg")) {
              this.resultShow = "error";
              this.returnData = "访问错误了！！\n" + response.data.errorMsg;
            } else {
              this.resultShow = "success";
              this.returnData = JSON.stringify(
                JSON.parse(response.data.ResponseData),
                null,
                2
              );
              return response.data.ResponseData;
            }
          } else {
            this.resultShow = "error";
            this.reuqustData = "返回结果为空";
          }
        })
        .then((res) => {
          if (res) {
            this.interAddData.interRelResult = res;
            this.interAddData.interName = this.interName;
            this.interAddData.interType = this.requestMethod;
            this.interAddData.interPath = this.requestUrl;
            this.interAddData.interParamHeader = this.combineHeader();
            this.interAddData.interParamBody = this.bodyValue();
            updateInterface(this.interAddData);
            return res;
          }
        })
        .then((dmsRes) => {
          if (dmsRes) {
            // 在变量表中，找到接口id对应的变量，正则匹配变量值然后修改
            interListGlobalvar(this.interAddData.id.toString()).then(
              (response) => {
                response.rows.forEach((elem) => {
                  if (
                    elem.varType === 3 &&
                    elem.varRules !== "" &&
                    elem.varRules !== null
                  ) {
                    let dmsRule = new RegExp(elem.varRules);
                    let res = dmsRule.exec(dmsRes);
                    if (res !== null) {
                      if (res.length === 1) {
                        elem.varValue = res[0];
                      } else if (res.length === 2) {
                        elem.varValue = res[1];
                      }
                    }
                    updateGlobalvar(elem);
                  }
                });
              }
            );
          }
        });
      this.returnResult = true;
    },
    saveRequest() {
      if (this.interName === "") {
        this.$message({
          showClose: true,
          message: "接口名称不能为空",
          type: "error",
        });
      } else {
        if (this.idCollection.interId === -1) {
          let reuqustData = {
            interName: this.interName,
            interType: this.requestMethod,
            interPath: this.requestUrl,
            interParamHeader: this.combineHeader(),
            interParamBody: this.bodyValue(),
            interOfpro: this.idCollection.proId,
          };
          addInterface(reuqustData)
            .then((response) => {
              this.$message({
                showClose: true,
                message: "添加成功",
                type: "success",
              });
            })
            .then((_) => {
              this.$emit("flashTreeNode");
              this.initPage();
            });
        } else {
          this.interAddData.interName = this.interName;
          this.interAddData.interType = this.requestMethod;
          this.interAddData.interPath = this.requestUrl;
          this.interAddData.interParamHeader = this.combineHeader();
          this.interAddData.interParamBody = this.bodyValue();
          if (this.interAddData.id === null || this.interAddData.id == "") {
            addInterface(this.interAddData)
              .then((response) => {
                this.$message({
                  showClose: true,
                  message: "复制成功",
                  type: "success",
                });
              })
              .then((_) => {
                this.$emit("flashTreeNode");
                this.initPage();
              });
          } else {
            updateInterface(this.interAddData)
              .then((response) => {
                this.$message({
                  showClose: true,
                  message: "修改成功",
                  type: "success",
                });
              })
              .then((_) => {
                this.$emit("flashTreeNode");
                this.initPage();
              });
          }
        }
      }
    },
    bodyValue() {
      // 进行判断之后给body赋值;
      if (this.formInline.radio === "none") {
        return JSON.stringify({
          bodyType: "none",
          bodyData: "",
        });
      }
      let data = {
        bodyType: this.formInline.radio,
        bodyData:
          this.formInline.radio === "formData"
            ? this.combineBody()
            : this.bodyTextData,
      };
      return JSON.stringify(data);
    },
    tableCellClassName({ row, column, rowIndex, columnIndex }) {
      this.cellClassNameMethod(row, rowIndex, column, columnIndex);
    },
    headerTableCellClassName({ row, column, rowIndex, columnIndex }) {
      this.cellClassNameMethod(row, rowIndex, column, columnIndex);
    },
    bodyTableCellClassName({ row, column, rowIndex, columnIndex }) {
      this.cellClassNameMethod(row, rowIndex, column, columnIndex);
    },
    cellClassNameMethod(row, rowIndex, column, columnIndex) {
      // console.log(row, column);
      this.$set(row, "index", rowIndex);
      // row.index = rowIndex;
      column.index = columnIndex;
    },
    cellClick(row, column, cell, event) {
      if (this.isEdit === false) {
        this.cellRowIndex = row.index;
        this.cellColumnIndex = column.index;
        this.$nextTick(() => {
          this.$refs["editInput"].focus();
        });
      }
    },
    headerCellClick(row, column, cell, event) {
      if (this.isEdit === false) {
        this.headerCellRowIndex = row.index;
        this.headerCellColumnIndex = column.index;
        this.$nextTick(() => {
          this.$refs["editInput"].focus();
        });
      }
    },
    bodyCellClick(row, column, cell, event) {
      if (this.isEdit === false) {
        this.bodyCellRowIndex = row.index;
        this.bodyCellColumnIndex = column.index;
        this.$nextTick(() => {
          this.$refs["editInput"].focus();
        });
      }
    },
    changeValue() {
      if (this.cellRowIndex + 1 === this.tableData.length) {
        // 如果有值了，就添加一行
        if (
          this.tableData[this.cellRowIndex].hasOwnProperty("key") ||
          this.tableData[this.cellRowIndex].hasOwnProperty("value")
        ) {
          this.tableData.push({});
        }
      }
      // 如果该行有key和value，则进行合并操作
      if (
        this.tableData[this.cellRowIndex].hasOwnProperty("key") ||
        this.tableData[this.cellRowIndex].hasOwnProperty("value")
      ) {
        this.combineParam();
      }
      this.cellRowIndex = null;
      this.cellColumnIndex = null;
    },
    headerChangeValue() {
      // console.log(this.headerData[this.headerCellRowIndex]);
      if (this.headerCellRowIndex + 1 === this.headerData.length) {
        // 如果有值了，就添加一行
        if (
          this.headerData[this.headerCellRowIndex].hasOwnProperty("key") ||
          this.headerData[this.headerCellRowIndex].hasOwnProperty("value")
        ) {
          this.headerData.push({});
        }
      }
      if (this.headerData.length > 1) {
        if (
          this.headerData[this.headerCellRowIndex].key === "" &&
          this.headerData[this.headerCellRowIndex].value === ""
        ) {
          this.headerData.splice(this.headerCellRowIndex, 1);
        }
      }
      this.headerCellRowIndex = null;
      this.headerCellColumnIndex = null;
    },
    bodyChangeValue() {
      if (this.bodyCellRowIndex + 1 === this.bodyData.length) {
        // 如果有值了，就添加一行
        if (
          this.bodyData[this.bodyCellRowIndex].hasOwnProperty("key") ||
          this.bodyData[this.bodyCellRowIndex].hasOwnProperty("value")
        ) {
          this.bodyData.push({});
        }
      }
      if (this.bodyData.length > 1) {
        if (
          this.bodyData[this.bodyCellRowIndex].key === "" &&
          this.bodyData[this.bodyCellRowIndex].value === ""
        ) {
          this.bodyData.splice(this.bodyCellRowIndex, 1);
        }
      }
      this.bodyCellRowIndex = null;
      this.bodyCellColumnIndex = null;
    },
    valueInit() {
      this.resultShow = "success";
      this.returnResult = false;
      this.activeName = "first";
      this.requestUrl = "";
      this.tableData = [{}];
      this.headerData = [{}];
      this.bodyData = [{}];
      this.interName = "";
      this.requestMethod = "1";
      this.bodyTextData = "";
      this.formInline = { radio: "none", value: "json" };
    },
    copyInter() {
      this.isEdit = false;
      this.AddOrEdit = "Add";
      this.loading = true;
      getInterface(this.idCollection.interId)
        .then((response) => {
          let res = response.data;
          // console.log(res);
          this.interAddData = response.data;
          this.interAddData.id = null;
          this.requestUrl = res.interPath;
          this.interName = res.interName;
          this.requestMethod = res.interType;
          this.segmentationParam();
          // 分割header
          this.segmentationHeader(res.interParamHeader);
          if (res.interRelResult !== "" && res.interRelResult !== null) {
            this.returnResult = true;
            this.returnData = JSON.stringify(
              JSON.parse(res.interRelResult),
              null,
              2
            );
          }
          // 判断body
          try {
            res.interParamBody = JSON.parse(res.interParamBody) || {
              bodyType: "none",
              bodyData: "",
            };
          } catch (error) {
            res.interParamBody = {
              bodyType: "none",
              bodyData: "",
            };
          }
          this.formInline.radio = res.interParamBody.bodyType || "none";
          if (res.interParamBody.bodyType === "formData") {
            this.segmentationBody(res.interParamBody.bodyData);
          }
          if (res.interParamBody.bodyType === "raw") {
            this.bodyTextData = res.interParamBody.bodyData;
          }
        })
        .then((_) => {
          this.loading = false;
        });
    },
    initPage() {
      // console.log(this.idCollection);
      this.valueInit();
      this.isEdit = true;
      // interId如果是-1，表示项目新增接口，proId为-1，表示编辑接口
      if (this.idCollection.interId === -1) {
        this.isEdit = false;
        this.AddOrEdit = "Add";
      } else {
        this.AddOrEdit = "Edit";
        this.loading = true;
        getInterface(this.idCollection.interId)
          .then((response) => {
            let res = response.data;
            // console.log(res);
            this.interAddData = response.data;
            this.requestUrl = res.interPath;
            this.interName = res.interName;
            this.requestMethod = res.interType;
            this.segmentationParam();
            // 分割header
            this.segmentationHeader(res.interParamHeader);
            if (res.interRelResult !== "" && res.interRelResult !== null) {
              this.returnResult = true;
              this.returnData = JSON.stringify(
                JSON.parse(res.interRelResult),
                null,
                2
              );
            }
            // 判断body
            try {
              res.interParamBody = JSON.parse(res.interParamBody) || {
                bodyType: "none",
                bodyData: "",
              };
            } catch (error) {
              res.interParamBody = {
                bodyType: "none",
                bodyData: "",
              };
            }
            this.formInline.radio = res.interParamBody.bodyType || "none";
            if (res.interParamBody.bodyType === "formData") {
              this.segmentationBody(res.interParamBody.bodyData);
            }
            if (res.interParamBody.bodyType === "raw") {
              this.bodyTextData = res.interParamBody.bodyData;
            }
            // if (res.interParamBody === null || res.interParamBody === "") {
            //   this.formInline.radio = "none";
            // } else if (/{/.test(res.interParamBody)) {
            //   this.formInline.radio = "raw";
            //   this.bodyTextData = res.interParamBody;
            // } else {
            //   this.formInline.radio = "formData";
            //   this.segmentationBody(res.interParamBody);
            // }
          })
          .then((_) => {
            this.loading = false;
          });
      }
    },
    // leaveTip() {
    //   this.$confirm("接口内容还未保存，是否直接离开?", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "info",
    //   })
    //     .then(() => {
    //       this.initPageFunc();
    //     })
    //     .catch(() => {});
    // },
    segmentationParam() {
      this.tableData = [{}];
      // example：http://localhost:8088/pro?id=1&status=0
      //1、判断url是否有?
      //2、判断url是否有&
      //3、判断url的&分割出的参数中，是否有=号
      let detemineQuestionMark = /\?/;
      let detemineConnector = /\&/;
      // let detemineEqualSign = /\=/;
      if (detemineQuestionMark.test(this.requestUrl)) {
        //如果有问号，则问号右边保存为参数列表
        this.url = this.requestUrl.split("?")[0];
        let paramString = this.requestUrl.split("?")[1];
        //参数列表中是否有&符号
        if (detemineConnector.test(paramString)) {
          //包含&符号
          let paramList = paramString.split("&");
          let paramListIndex = 0;
          paramList.forEach((elem) => {
            let tempKey = elem.split("=")[0];
            let tempValue = elem.split("=")[1];

            this.$set(this.tableData, paramListIndex, {
              key: tempKey,
              value: tempValue,
            });
            paramListIndex += 1;
          });
        } else {
          //不包含&符号
          let tempKey = paramString.split("=")[0];
          let tempValue = paramString.split("=")[1];
          this.$set(this.tableData, 0, {
            key: tempKey,
            value: tempValue,
          });
        }
        this.tableData.push({});
      } else {
        this.url = this.requestUrl;
      }
    },
    combineParam() {
      this.requestUrl = "";
      this.requestUrl += this.url + "?";
      this.tableData.forEach((elem) => {
        if (elem.hasOwnProperty("key") || elem.hasOwnProperty("value")) {
          if (elem.key !== "" || elem.value !== "") {
            if (elem.index === 0) {
              this.requestUrl += (elem.key || "") + "=" + (elem.value || "");
            } else {
              this.requestUrl +=
                "&" + (elem.key || "") + "=" + (elem.value || "");
            }
          }
        }
      });
    },
    segmentationHeader(headerData) {
      if (headerData.length !== 0) {
        let headeList = headerData.split("\n");
        let headerIndex = 0;
        headeList.forEach((elem) => {
          let tempKey = elem.split(": ")[0];
          let tempValue = elem.split(": ")[1];
          this.$set(this.headerData, headerIndex, {
            key: tempKey,
            value: tempValue,
          });
          headerIndex += 1;
        });
        this.headerData.push({});
      }
    },
    combineHeader() {
      let res = "";
      this.headerData.forEach((elem) => {
        if (elem.hasOwnProperty("key") || elem.hasOwnProperty("value")) {
          res += (elem.key || "") + ": " + (elem.value || "") + "\n";
        }
      });
      return res.slice(0, res.length - 1) || "";
    },
    segmentationBody(bodyData) {
      if (bodyData.length !== 0) {
        let bodyList = bodyData.split("&");
        let bodyIndex = 0;
        bodyList.forEach((elem) => {
          let tempKey = elem.split("=")[0];
          let tempValue = elem.split("=")[1];
          this.$set(this.bodyData, bodyIndex, {
            key: tempKey,
            value: tempValue,
          });
          bodyIndex += 1;
        });
        this.bodyData.push({});
      }
    },
    combineBody() {
      let res = "";
      this.bodyData.forEach((elem) => {
        if (elem.hasOwnProperty("key") || elem.hasOwnProperty("value")) {
          if (elem.index === 0) {
            res += (elem.key || "") + "=" + (elem.value || "");
          } else {
            res += "&" + (elem.key || "") + "=" + (elem.value || "");
          }
        }
      });
      return res;
    },
    // deleteRow(index, rows) {
    //   rows.splice(index, 1);
    //   this.combineParam();
    // },
  },
};
</script>

<style scoped>
.tab-content {
  width: 100%;
  height: 300px;
  /* border: 2px solid black; */
  border-bottom: 1px solid #dcdfe6;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
  font-weight: bolder;
}
.radioMenu {
  border-bottom: 1px #dcdfe6 solid;
}
.showInfo {
  width: 100%;
  height: 220px;
  /* background-color: gray; */
}
.none-style {
  text-align: center;
  padding-top: 10px;
  color: #909399;
}
.title {
  margin-top: 10px;
  color: #909399;
}
.response-content {
  width: 100%;
  height: 280px;
  /* border: 1px solid #dcdfe6; */
  text-align: center;
}
.response-content > div > img {
  width: 300px;
  height: 270px;
}
</style>
